// 生成器函数
function * foo () {
  console.log('start')
  try {
    const res = yield 'foo'
    console.log(res)
  } catch (e) {
    console.log(e)
  }
}

const generator = foo()
const result = generator.next()
console.log(result)
generator.next('bar')
// generator.throw(new Error('g error'))

function ajax(url) {
  return new Promise(function (resolve, reject) {
    const xhr = new XMLHttpRequest()
    xhr.open('GET', url)
    xhr.responseType = 'json'
    xhr.onload = function () {
      if (this.status === 200) {
        resolve(this.response)
      } else {
        reject(new Error(this.statusText))
      }
    }
    xhr.send()
  })
}

function * main () {
  try {
    const users = yield ajax('api/users.json')
    console.log(users)
    const posts = yield ajax('api/posts.json')
    console.log(posts)
  } catch (e) {
    console.log(e)
  }
}

function co (generator) {
  const m = generator()
  const resultAjax = m.next()

  function resultLoop (result) {
    if (result.done) return
    result.value.then(data => {
      const res = m.next(data)
      resultLoop(res)
    }, err => {
      m.throw(err)
    })
  }
  resultLoop(resultAjax)
}

co(main)


// resultAjax.value.then(data => {
//   const resultAjax2 = m.next(data)
//   if (resultAjax2.done) return
//   resultAjax2.value.then(data => {
//     const resultAjax3 = m.next(data)
//     if (resultAjax3.done) return
//   })
// })

